<?php
/**
 * 零起飞-(07FLY-CRM)
 * ==============================================
 * 版权所有 2015-2028   成都零起飞网络，并保留所有权利。
 * 网站地址: http://www.07fly.xyz
 * ----------------------------------------------
 * 如果商业用途务必到官方购买正版授权, 以免引起不必要的法律纠纷.
 * ==============================================
 * WorkflowNodeor: kfrs <goodkfrs@QQ.com> 574249366
 * Date: 2019-10-3
 */

namespace app\workflow\logic;

use think\Db;
use think\Request;

/**
 * 流程节点=》逻辑层
 */
class WorkflowNode extends WorkflowBase
{
    /**
     * 流程节点列表
     * @param array $where
     * @param bool $field
     * @param string $order
     * @param int|mixed $paginate
     * @return
     */
    public function getWorkflowNodeList($where = [], $field = true, $order = '', $paginate = DB_LIST_ROWS)
    {
        $list = $this->modelWorkflowNode->getList($where, $field, $order, $paginate)->toArray();
        if($paginate===false) $list['data']=$list;
        foreach ($list['data'] as &$row){
            $row['create_user_name']=$this->modelSysUser->getValue(['id'=>$row['create_user_id']],'realname');
            $row['destribute_type_name']=$this->modelWorkflowNode->destribute_type($row['destribute_type'])['name'];
        }
        return $list;
    }

    /**
     * 流程节点添加
     * @param array $data
     * @return array
     */
    public function workflowNodeAdd($data = [])
    {

        $validate_result = $this->validateWorkflowNode->scene('add')->check($data);
        if (!$validate_result) {
            return [RESULT_ERROR, $this->validateWorkflowNode->getError()];
        }
        //指定分类类型为用户时，必须选择审批人员
        $destype=$this->logicWorkflowNode->getDestributeType($data['destribute_type']);

        if(!empty($destype['link']) && empty($data['destribute_user_id'])){
            return [RESULT_ERROR, '分配类型为批定用户，必须选择审批人员'];
            exit;
        }

        $data['create_user_id']=SYS_USER_ID;

        $data['workflow_node_id'] = $this->modelWorkflowNode->setInfo($data);

        //添加节点关联人员
        $result=$this->logicWorkflowNodeUser->workflowNodeUserAdd($data);

        //按排序更新节点步骤
        $this->updateNodeSort($data['workflow_id']);

        $result && action_log('新增', '新增WorkflowNodeNode：' . $data['name']);
        $url = url('show');
        return $result ? [RESULT_SUCCESS, '添加成功', $url] : [RESULT_ERROR, $this->modelWorkflowNode->getError()];
    }

    /**
     * 流程节点编辑
     * @param array $data
     * @return array
     */
    public function workflowNodeEdit($data = [])
    {

        $validate_result = $this->validateWorkflowNode->scene('edit')->check($data);
        if (!$validate_result) {
            return [RESULT_ERROR, $this->validateWorkflowNode->getError()];
        }

        $this->modelWorkflowNode->setInfo($data);

        $data['workflow_node_id']=$data['id'];

        //添加节点关联人员
        $result=$this->logicWorkflowNodeUser->workflowNodeUserAdd($data);

        //按排序更新节点步骤
        $this->updateNodeSort($data['workflow_id']);

        $url = url('show');
        $result && action_log('编辑', '编辑WorkflowNodeNode，name：' . $data['name']);
        return $result ? [RESULT_SUCCESS, '编辑成功', $url] : [RESULT_ERROR, $this->modelWorkflowNode->getError()];
    }

    /**
     * 流程节点删除
     * @param array $where
     * @return array
     */
    public function workflowNodeDel($where = [])
    {
        $map['workflow_node_id']=$where['id'];
        $this->logicWorkflowNodeUser->workflowNodeUserDel($map);

        $result = $this->modelWorkflowNode->deleteInfo($where,true);
        $result && action_log('删除', '删除WorkflowNodeNode，where：' . http_build_query($where));
        return $result ? [RESULT_SUCCESS, '删除成功'] : [RESULT_ERROR, $this->modelWorkflowNode->getError()];
    }

    /**流程节点信息
     * @param array $where
     * @param bool $field
     * @return
     */
    public function getWorkflowNodeInfo($where = [], $field = true)
    {
        return $this->modelWorkflowNode->getInfo($where, $field);
    }


    /**
     * 流程节点排序
     * @param array $data
     * @return array
     */
    public function updateNodeSort($workflow_id)
    {
        $list = $this->modelWorkflowNode->getList(['workflow_id'=>$workflow_id],'id,sort','sort asc',false);
        $uptData=[];
        foreach ($list as $key=>&$row){
            $uptData[$key]['id']=$row['id'];
            $uptData[$key]['sort']=$key+1;
        }
        $this->modelWorkflowNode->setList($uptData,true);
    }


    /**
     * 节点分配类型
     *
     * @param null $key
     * @return mixed
     * Author: kfrs <goodkfrs@QQ.com> created by at 2020/10/28 0028
     */
    public function  getDestributeType($key=null){
        return $this->modelWorkflowNode->destribute_type($key);
    }


    /**
     * 获取列表搜索条件
     */
    public function getWhere($data = [])
    {

        $where = [];
        //关键字查
        !empty($data['keywords']) && $where['name|content'] = ['like', '%' . $data['keywords'] . '%'];
        !empty($data['workflow_id']) && $where['workflow_id'] = ['=',  $data['workflow_id']];

        //下次联系时间
        if (!empty($data['next_rangedate'])) {
            $range_date = str2arr($data['next_rangedate'], "-");
            $where['next_time'] = ['between', $range_date];
        }
            //print_r($where);exit;

        return $where;
    }

    /**
     * 获取排序条件
     */
    public function getOrderBy($data = [])
    {
        $order_by = "";
        if (!empty($data['orderField'])) {
            $orderField = $data['orderField'];
            $orderDirection = $data['orderDirection'];
        } else {
            $orderField = "";
            $orderDirection = "";
        }
        if ($orderField == 'by_link') {
            $order_by = "link_time $orderDirection";
        } else if ($orderField == 'by_next') {
            $order_by = "next_time $orderDirection";
        } else if ($orderField == 'by_nodays') {
            $order_by = "nodays $orderDirection";
        } else {
            $order_by = "sort asc";
        }
        return $order_by;
    }


    /**
     * 获得流程=》下一节点
     * @param $wfid
     * @param $nid
     * @return   number 0=结束节点或者未找到  ; >0表示查询节点
     * Author: kfrs <goodkfrs@QQ.com> created by at 2020/10/28 0028
     */
    public function getWorkflowNodeNext($wfid, $nid=0){
        $sort=0;
        if($nid>0){
            $map['workflow_id']=['=',$wfid];
            $map['id']=['=',$nid];
            $sort=$this->modelWorkflowNode->getValue($map, 'sort');
        }
        $map2['workflow_id']=['=',$wfid];
        $map2['sort']=['>',$sort];
        $node_id=$this->modelWorkflowNode->getValue($map2, 'id');
        if($node_id){
            return $node_id;
        }else{
            return 0;
        }
    }

    /**
     * 获得流程+》上一节点
     * @param $wfid 流程编号ID
     * @param $nid  当前节点ID
     * Author: kfrs <goodkfrs@QQ.com> created by at 2020/10/28 0028
     */
    public function getWorkflowNodePrev($wfid,$nid){
        $map['workflow_id']=['=',$wfid];
        $map['id']=['=',$nid];
        $sort=$this->modelWorkflowNode->getValue($map, 'sort');

        $map2['workflow_id']=['=',$wfid];
        $map2['sort']=['<',$sort];
        $node_id=$this->modelWorkflowNode->getValue($map2, 'id');
        if($node_id){
            return $node_id;
        }else{
            return 0;
        }
    }

    /**
     * 获得流程=》处理人相关信息
     * @param $wfid             流程编号ID
     * @param $apply_user_id    申请人
     * @return array([id=>0,name='姓名'],...)
     * Author: kfrs <goodkfrs@QQ.com> created by at 2020/10/28 0028
     */
    public function getWorkflowNodeDealInfo($nid,$apply_user_id){
        $deal_user_info=[
            'deal_list'=>0,
            'sign_type'=>0,
        ];
        $map['id']=['=',$nid];
        $nodeinfo=$this->modelWorkflowNode->getInfo($map)->toArray();
        if($nodeinfo){
            //1=负责人主管 2=指定用户(任意一人)  3=指定用户(多人会签) 4=上一级审批人主管
            switch ($nodeinfo['destribute_type'])
            {
                case 1:
                    $list[0]=$this->logicSysUser->getSysUserSuperior($apply_user_id);
                    $deal_user_info['deal_list']=$list;
                    $deal_user_info['sign_type']=0;
                    break;
                case 2:
                    $deal_user_info['deal_list']=$this->modelWorkflowNodeUser->getList(['workflow_node_id'=>$nid],'deal_user_id as id,deal_user_name as realname','',false);
                    $deal_user_info['sign_type']=2;
                    break;
                case 3:
                    $deal_user_info['deal_list']=$this->modelWorkflowNodeUser->getList(['workflow_node_id'=>$nid],'deal_user_id as id,deal_user_name as realname','',false);
                    $deal_user_info['sign_type']=3;
                    break;
            }
        }
        return $deal_user_info;
    }

}
